<template>
  <div>
    <div class="search-term">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
        <el-form-item label="路径">
          <el-input v-model="searchInfo.path" placeholder="路径" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="searchInfo.description" placeholder="描述" />
        </el-form-item>
        <el-form-item label="api组">
          <el-input v-model="searchInfo.apiGroup" placeholder="api组" />
        </el-form-item>
        <el-form-item label="请求">
          <el-select v-model="searchInfo.method" clearable placeholder="请选择">
            <el-option
              v-for="item in methodOptions"
              :key="item.value"
              :label="`${item.label}(${item.value})`"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="openDialog('addApi')">新增api</el-button>
        </el-form-item>
        <el-form-item>
          <el-popconfirm
            title="确认删除？"
            confirm-button-text="确定"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            placement="bottom-end"
            @confirm="onDelete"
            @cancel="deleteVisible = false"
          >
            <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini">批量删除</el-button>
          </el-popconfirm>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="tableData" border stripe @sort-change="sortChange" @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column label="id" width="100" prop="ID" sortable="custom" />
      <el-table-column label="api路径" prop="path" sortable="custom" />
      <el-table-column label="api简介" prop="description" sortable="custom" />
      <el-table-column label="api分组" width="240" prop="apiGroup" sortable="custom" />
      <el-table-column label="请求" width="113" prop="method" sortable="custom">
        <template slot-scope="scope">
          <div>
            <el-tag
              :key="scope.row.methodFiletr"
              :type="scope.row.method|tagTypeFiletr"
              effect="dark"
              size="mini"
            >{{ scope.row.method|methodFiletr }}</el-tag>
            {{ scope.row.method }}
          </div>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="158">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="editApi(scope.row)">编辑</el-button>
          <el-popconfirm
            title="确认删除？"
            confirm-button-text="确定"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            placement="top-end"
            @confirm="deleteApi(scope.row)"
          >
            <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini" style="margin-left: 10px">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="page"
      :page-size="pageSize"
      :page-sizes="[10, 30, 50, 100]"
      :style="{float:'right',padding:'20px'}"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />

    <el-dialog :before-close="closeDialog" :title="dialogTitle" :visible.sync="dialogFormVisible" width="40%" top="5vh">
      <el-form ref="apiForm" :model="form" :rules="rules" label-position="top">
        <el-form-item v-show="!form.public" label="所属菜单" :prop="form.public? '' : checkboxValue? 'menuId' : ''">
          <el-cascader
            v-model="form.menuId"
            :options="menuOptions"
            :props="{ expandTrigger: 'hover', label: 'title', value: 'ID' }"
            filterable
            style="width: calc(100% - 80px)"
            :disabled="!checkboxValue"
          />
          <el-checkbox v-model="checkboxValue" style="float: right">选择项</el-checkbox>
        </el-form-item>
        <el-form-item v-show="!form.public" label="所属按钮" :prop="form.public? '' : checkboxValue? '' : 'buttonId'">
          <el-cascader
            v-model="form.buttonId"
            :options="buttonOptions"
            :props="{ expandTrigger: 'hover', label: 'cname', value: 'ID' }"
            filterable
            style="width: calc(100% - 80px)"
            :disabled="checkboxValue"
          />
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="form.path" autocomplete="off" style="width: 100%" />
        </el-form-item>
        <el-form-item label="请求" prop="method">
          <el-select v-model="form.method" placeholder="请选择" style="width: 100%">
            <el-option
              v-for="item in methodOptions"
              :key="item.value"
              :label="`${item.label}(${item.value})`"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="api分组" prop="apiGroup">
          <el-input v-model="form.apiGroup" autocomplete="off" style="width: 100%" />
        </el-form-item>
        <el-form-item label="api简介" prop="description">
          <el-input v-model="form.description" autocomplete="off" style="width: 100%" />
        </el-form-item>
        <el-form-item label="是否为公用API" prop="public">
          <el-radio-group v-model="form.public">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div class="warning">新增Api需要在角色管理内配置权限才可使用</div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="enterDialog">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 获取列表内容封装在mixins内部  getTableData方法 初始化已封装完成 条件搜索时候 请把条件安好后台定制的结构体字段 放到 this.searchInfo 中即可实现条件搜索
import { getMenuList } from '@/api/menu'
import { getAllButtons } from '@/api/sysButton'

import {
  getApiById,
  getApiList,
  createApi,
  updateApi,
  deleteApi,
  deleteApisByIds
} from '@/api/api'
import infoList from '@/mixins/infoList'
import { toSQLLine } from '@/utils/stringFun'
const methodOptions = [
  {
    value: 'POST',
    label: '增',
    type: 'success'
  },
  {
    value: 'GET',
    label: '查',
    type: ''
  },
  {
    value: 'PUT',
    label: '改',
    type: 'warning'
  },
  {
    value: 'DELETE',
    label: '删',
    type: 'danger'
  }
]

export default {
  name: 'Api',
  filters: {
    methodFiletr(value) {
      const target = methodOptions.filter(item => item.value === value)[0]
      // return target && `${target.label}(${target.value})`
      return target && `${target.label}`
    },
    tagTypeFiletr(value) {
      const target = methodOptions.filter(item => item.value === value)[0]
      return target && `${target.type}`
    }
  },
  mixins: [infoList],
  data() {
    return {
      deleteVisible: false,
      listApi: getApiList,
      dialogFormVisible: false,
      dialogTitle: '新增Api',
      apis: [],
      form: {
        path: '',
        apiGroup: '',
        method: '',
        description: '',
        menuId: '',
        buttonId: '',
        public: false
      },
      checkboxValue: false,
      methodOptions: methodOptions,
      menuOptions: [],
      buttonOptions: [],
      type: '',
      rules: {
        menuId: [
          {
            required: true,
            message: '请选择所属菜单',
            trigger: 'blur'
          }
        ],
        public: [
          {
            required: true,
            message: '请选择是否为公用API',
            trigger: 'blur'
          }
        ],
        buttonId: [
          {
            required: true,
            message: '请选择所属按钮',
            trigger: 'blur'
          }
        ],
        path: [{ required: true, message: '请输入api路径', trigger: 'blur' }],
        apiGroup: [
          { required: true, message: '请输入组名称', trigger: 'blur' }
        ],
        method: [
          { required: true, message: '请选择请求方式', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入api介绍', trigger: 'blur' }
        ]
      }
    }
  },
  // watch: {
  //   checkboxValue: {
  //     handler(newVal, oldVal) {},
  //     deep: true
  //   }
  // },
  created() {
    this.getTableData()
    this.getMenuList()
    this.getAllButtons()
  },
  methods: {
    // 获取菜单
    getMenuList() {
      const params = {
        page: 1,
        pageSize: 999
      }
      getMenuList(params).then((res) => {
        if (res.code === 0) {
          this.menuOptions = res.data.list
        }
      })
    },
    // 获取按钮
    getAllButtons() {
      const params = {
        parentId: '0'
      }
      getAllButtons(params).then((res) => {
        if (res.code === 0) {
          this.buttonOptions = this.buildButtonTree(res.data.buttons)
        }
      })
    },
    // 创建button树方法
    buildButtonTree(buttons) {
      const buttonObj = {}
      buttons &&
        buttons.map(item => {
          item.onlyId = item.ID
          if (item.buttonGroup in buttonObj) {
            buttonObj[item.buttonGroup].push(item)
          } else {
            Object.assign(buttonObj, { [item.buttonGroup]: [item] })
          }
        })
      const buttonTree = []
      for (const key in buttonObj) {
        const treeNode = {
          ID: key,
          cname: key + '组',
          children: buttonObj[key]
        }
        buttonTree.push(treeNode)
      }
      return buttonTree
    },
    //  选中api
    handleSelectionChange(val) {
      this.apis = val
    },
    async onDelete() {
      const ids = this.apis.map(item => item.ID)
      const res = await deleteApisByIds({ ids })
      if (res.code === 0) {
        this.$notify({
          type: 'success',
          title: '成功',
          message: res.msg
        })
        if (this.tableData.length === ids.length && this.page > 1) {
          this.page--
        }
        this.deleteVisible = false
        this.getTableData()
      }
    },
    // 排序
    sortChange({ prop, order }) {
      if (prop) {
        this.searchInfo.orderKey = toSQLLine(prop)
        this.searchInfo.desc = order === 'descending'
      }
      this.getTableData()
    },
    // 条件搜索前端看此方法
    onSubmit() {
      this.page = 1
      this.pageSize = 10
      this.getTableData()
    },
    initForm() {
      this.$refs.apiForm.resetFields()
      this.form = {
        path: '',
        apiGroup: '',
        method: '',
        description: ''
      }
    },
    closeDialog() {
      this.initForm()
      this.dialogFormVisible = false
    },
    openDialog(type) {
      switch (type) {
        case 'addApi':
          this.dialogTitle = '新增Api'
          break
        case 'edit':
          this.dialogTitle = '编辑Api'
          break
        default:
          break
      }
      this.type = type
      this.dialogFormVisible = true
    },
    async editApi(row) {
      const res = await getApiById({ id: row.ID })
      this.form = res.data.api
      this.openDialog('edit')
    },
    async deleteApi(row) {
      const res = await deleteApi(row)
      if (res.code === 0) {
        this.$notify({
          type: 'success',
          title: '成功',
          message: '删除成功!'
        })
        if (this.tableData.length === 1 && this.page > 1) {
          this.page--
        }
        this.getTableData()
      }
    },
    async enterDialog() {
      this.$refs.apiForm.validate(async valid => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.form))
          if (this.checkboxValue) {
            params.bottonId = ''
            if (Array.isArray(params.menuId)) {
              params.menuId = params.menuId[params.menuId.length - 1]
            }
          } else {
            params.menuId = ''
            if (Array.isArray(params.bottonId)) {
              params.bottonId = params.bottonId[params.bottonId.length - 1]
            }
          }
          switch (this.type) {
            case 'addApi':
              {
                const res = await createApi(params)
                if (res.code === 0) {
                  this.$notify({
                    type: 'success',
                    title: '成功',
                    message: '添加成功'
                  })
                }
                this.getTableData()
                this.closeDialog()
              }

              break
            case 'edit':
              {
                const res = await updateApi(params)
                if (res.code === 0) {
                  this.$notify({
                    type: 'success',
                    title: '成功',
                    message: '编辑成功!'
                  })
                }
                this.getTableData()
                this.closeDialog()
              }
              break
            default:
              // eslint-disable-next-line no-lone-blocks
              {
                this.$notify({
                  type: 'error',
                  title: '错误',
                  message: '未知操作'
                })
              }
              break
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.el-form-item {
    margin-bottom: 0;
}
.button-box {
  .el-button {
    float: right;
  }
}
.el-tag--mini {
  margin-left: 5px;
}
.warning {
  color: #dc143c;
}
</style>
